package com.lottery.htbc.dao;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.lottery.htbc.dto.SynRecordDto;
import com.lottery.htbc.mapper.BetRecordMapper;
import com.lottery.htbc.mapper.BetTaskMapper;
import com.lottery.htbc.mapper.SynRecordMapper;
import com.lottery.htbc.pojo.BetRecord;
import com.lottery.htbc.pojo.BetTask;
import com.lottery.htbc.pojo.SynRecord;

@Service
public class SynchroRecordDao {
	/**
	 * 未同步
	 */
	private static final int IS_SYN_NOT=-1;
	/**
	 * 已经同步
	 */
	private static final int IS_SYN_FINISH=1;

	@Autowired
	private SynRecordMapper synRecordMapper;

	@Autowired
	private BetTaskMapper  betTaskMapper;

	@Autowired
	private BetRecordMapper  betRecordMapper;

	/**
	 * 插入待同步的记录
	 * @param syn
	 */
	public void  save(SynRecord syn){
		syn.setIsSyn(IS_SYN_NOT);
		syn.setCreated(new Date());
		syn.setUpdated(new Date());
		synRecordMapper.insertSelective(syn);

	}

	public List<SynRecord> queryNotSyn() {
		SynRecord param=new SynRecord();
		param.setIsSyn(IS_SYN_NOT);
		return synRecordMapper.select(param);

	}

	public void syncFinish(List<SynRecordDto> synDtos) {
		List<BetRecord> betRecords=new ArrayList<BetRecord>();
		List<BetTask> betTasks=new ArrayList<BetTask>();
		List<SynRecord> syns=new ArrayList<SynRecord>();
		for(SynRecordDto synDto:synDtos){
			SynRecord syn=synDto;
			syn.setIsSyn(IS_SYN_FINISH);
			if(syn.getWinAmount()!=null&&syn.getThrowAmount()!=null){
				syn.setProfitAmount(syn.getWinAmount()-syn.getThrowAmount());
			}
			syns.add(syn);
			betRecords.add(synDto.getBetRecord());
			BetTask task=synDto.getBetTask();
			if(task!=null&&task.getWinAmount()!=null&&task.getThrowAmount()!=null){
				task.setProfitAmount(task.getWinAmount()-task.getThrowAmount());
			}
			betTasks.add(task);
		}
		//批量修改 betTasks
		betTaskMapper.cumulationBatchByTaskId(betTasks);
		//批量修改 syns
		synRecordMapper.updateBatch(syns);
		//批量新增 betRecords
		betRecordMapper.saveBatch(betRecords);
	}

	/**
	 * 每月的数据备份
	 */
	public void backupsTableDataByMonth(String ym){
		//修改表名
		synRecordMapper.alterTabeName(ym);
		//copy之前的表结构
		synRecordMapper.copyTabeLkie(ym);
	}

}
